package cn.lls.controller.ca;


import cn.lls.base.result.R;
import cn.lls.entity.sys.EmployeeRoleEntity;
import cn.lls.entity.sys.RoleEntity;
import cn.lls.req.company.ConditionSearchRoleReq;
import cn.lls.req.company.RoleUpsertReq;
import cn.lls.service.*;
import cn.lls.vo.company.RoleInfo;
import cn.lls.vo.company.RoleInfoVO;
import cn.lls.vo.permission.PermissionSimpleVO;
import cn.lls.vo.permission.PermissionVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 划水艺术家
 * @since 2022-11-15
 */
@RestController
@Api(tags = "公司角色控制器")
@RequestMapping("/ca/role")
@Slf4j
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IEmployeeRoleService employeeRoleService;


    @Autowired
    private IRolePermissionService rolePermissionService;

    @PostMapping("/info")
    @ApiOperation(value = "分页条件查询本公司角色信息", notes = "分页条件查询本公司角色信息", response = R.class, httpMethod = "POST")
    public R getRoleInfoByPageAndCondition(@RequestBody @Validated
                                                          ConditionSearchRoleReq conditionSearchRoleReq,
                                              BindingResult bindingResult){
        conditionSearchRoleReq.setRoleName(conditionSearchRoleReq.getRoleName().trim());
        IPage<RoleInfo> roleInfoByPageAndCondition = roleService.getRoleInfoByPageAndCondition(conditionSearchRoleReq);
        RoleInfoVO roleInfoVO = new RoleInfoVO();
        roleInfoVO.setTotal(roleInfoByPageAndCondition.getTotal());
        roleInfoVO.setRecords(roleInfoByPageAndCondition.getRecords().stream().map((item)->{
            RoleInfo roleInfo = new RoleInfo();
            BeanUtils.copyProperties(item, roleInfo);
            // 该角色权限
            List<PermissionVO> permissionsByRoleId = permissionService.getPermissionsByRoleId(roleInfo.getRoleId());
            List<PermissionSimpleVO> psv = permissionsByRoleId.stream().map((item2)->{
                PermissionSimpleVO permissionSimpleVO = new PermissionSimpleVO();
                BeanUtils.copyProperties(item2, permissionSimpleVO);
                return permissionSimpleVO;
            }).collect(Collectors.toList());
            roleInfo.setPermissions(psv);
            return roleInfo;
        }).collect(Collectors.toList()));
        return R.success(roleInfoVO);
    }

    @GetMapping("/{roleId}")
    @ApiOperation(value = "根据Id查询角色信息", notes = "根据Id查询角色信息", response = R.class, httpMethod = "GET")
    public R getRoleDetailById(@ApiParam(required = true, value = "角色Id")
                                   @PathVariable("roleId")
                                   @NotEmpty(message = "角色Id不能为空") Long roleId){

        RoleInfo roleInfo = new RoleInfo();
        // 角色基本信息
        RoleEntity roleEntity = roleService.getById(roleId);
        BeanUtils.copyProperties(roleEntity, roleInfo);
        // 创建时间
        roleInfo.setCreateTime(roleEntity.getCreateTime().toString());
        // 所在部门的部门名称
        roleInfo.setDepartmentName(departmentService.getById(roleEntity.getDepartmentId()).getDepartmentName());
        // 该角色人数
        LambdaQueryWrapper<EmployeeRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmployeeRoleEntity::getRoleId, roleId);
        roleInfo.setRolePeopleCount(employeeRoleService.count(queryWrapper));
        // 该角色权限
        List<PermissionVO> permissionsByRoleId = permissionService.getPermissionsByRoleId(roleId);
        List<PermissionSimpleVO> psv = permissionsByRoleId.stream().map((item)->{
            PermissionSimpleVO permissionSimpleVO = new PermissionSimpleVO();
            BeanUtils.copyProperties(item, permissionSimpleVO);
            return permissionSimpleVO;
        }).collect(Collectors.toList());
        roleInfo.setPermissions(psv);
        return R.success(roleInfo);
    }


    @GetMapping("/select/{departmentId}")
    @ApiOperation(value = "根据departmentId查询角色信息", notes = "根据departmentId查询角色信息", response = R.class, httpMethod = "GET")
    public R getRoleSByDepartmentId(@ApiParam(required = true, value = "角色Id")
                               @PathVariable("departmentId")
                               @NotEmpty(message = "部门Id不能为空") Long departmentId){

        LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleEntity::getDepartmentId, departmentId);
        return R.success(roleService.list(queryWrapper));
    }



    @ApiOperation(value = "删除角色", notes = "根据Id删除角色，若该角色有人则无法删除", response = R.class, httpMethod = "DELETE")
    @DeleteMapping("/{roleId}")
    public R delPermission(
            @ApiParam(required = true, value = "角色Id")
            @PathVariable("roleId")
            @NotEmpty(message = "角色Id不能为空") Long roleId){
        roleService.delRole(roleId);
        return R.success();
    }

    @ApiOperation(value = "添加角色信息", notes = "添加角色信息", response = R.class, httpMethod = "POST")
    @PostMapping
    public R addRole(
            @Validated @RequestBody RoleUpsertReq roleUpsertReq,
            BindingResult bindingResult){
        log.info("rolkeUpsert req = {}", roleUpsertReq);
        roleService.addRole(roleUpsertReq);
        return R.success();
    }

    @ApiOperation(value = "更改角色信息", notes = "更改角色信息", response = R.class, httpMethod = "PUT")
    @PutMapping
    public R updateRole(
            @Validated @RequestBody RoleUpsertReq roleUpsertReq,
            BindingResult bindingResult){

        log.info("更改角色信息 req = {}", roleUpsertReq);
        roleService.updateRole(roleUpsertReq);
        return R.success();
    }

}

